package com.chenjt.juc.three_completableFuture;

import java.util.concurrent.*;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/6 9:51
 */
public class CompletableFutureBuildDemo {


    public static void main(String[] args) throws ExecutionException, InterruptedException {


//        noThreadPoolVoid();
//        haveThreadPoolVoid();

        noThreadPoolResult();


    }


    /**
     *  不 指定线程池 无 返回值的做法
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void noThreadPoolVoid() throws ExecutionException, InterruptedException {

        /**
         * 输出结果：
         * ForkJoinPool.commonPool-worker-1
         * null
         */
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(completableFuture.get());

    }


    /**
     *  指定 线程池 无 返回值的做法
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void haveThreadPoolVoid() throws ExecutionException, InterruptedException {

        /**
         * 输出结果：
         * pool-1-thread-1
         * null
         */
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },threadPool);

        System.out.println(completableFuture.get());

        threadPool.shutdown();

    }

    /**
     * 不 指定线程池 有 返回值的做法
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void noThreadPoolResult() throws ExecutionException, InterruptedException {

        /**
         * 运行结果：
         * ForkJoinPool.commonPool-worker-1
         * hello supplyAsync
         */
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello supplyAsync";
        });

        System.out.println(completableFuture.get());


    }

}
